package com.jiaai.web.zfp.callback;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.jiaai.pay.IPayAPI;
import com.jiaai.pay.entitiy.AlipayCallbackVO;
import com.jiaai.pay.entitiy.VPay;
import comm.utils.pay.alipay.Alipay;
import comm.utils.pay.comm.util.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Map;

/**
 * class_name:WeiXinCallBackController
 * describe:------------------>支付宝支付异步通知
 * create_user:张昉平
 * create_date:2018/1/29
 * create_time:12:27
 */
@RestController
@RequestMapping("/api/v1/alipay")
public class AlipayCallBackController {

    private static final Logger xlog = LoggerFactory.getLogger(AlipayCallBackController.class);

    @Reference
    private IPayAPI payAPI;

    @RequestMapping("/appPayNotify")
    public String appPayNotify(HttpServletRequest request, HttpServletResponse response){
        Map<String, String> params = HttpClientUtil.getRequestParams(request);
        xlog.error(JSONObject.toJSONString(params));

        AlipayCallbackVO data = new AlipayCallbackVO();
        data.setOut_trade_no(params.get("out_trade_no"));
        data.setTotal_amount(params.get("total_amount"));
        data.setSeller_id(params.get("seller_id"));
        data.setApp_id(params.get("app_id"));
        data.setTrade_status(params.get("trade_status"));
        data.setTrade_no(params.get("trade_no"));

        VPay order = payAPI.getOneOrder(params.get("out_trade_no"));

        if (order == null){//没有该订单
            return "failure";
        }
        if (order.getSettlementCode()==1){//已经结算了
            return "success";
        }
        if (order.getPrice().compareTo(new BigDecimal(data.getTotal_amount())) != 0){//数额不对
            return "failure";
        }
        if (!order.getVerifyId().equals(data.getApp_id())){//appid不对
            return "failure";
        }

        //一定要校验签名
        boolean isCorrectSign = Alipay.asynCheck(params, order.getVerifySecret());
        if (isCorrectSign){
            boolean flag = payAPI.checkAlipayCallback(data);
            if (flag){
                return "success";
            }
        }
        return "failure";
    }

}
